package com.mes.cloud.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mes.cloud.api.dto.request.area.BaseAreaEmployeePageRequest;
import com.mes.cloud.api.dto.request.area.BaseAreaListRequest;
import com.mes.cloud.api.dto.request.area.BaseAreaQueryPageRequest;
import com.mes.cloud.api.dto.request.area.BaseAreaRequest;
import com.mes.cloud.api.dto.request.organization.BaseOrganizationAreaPageRequest;
import com.mes.cloud.api.dto.response.area.*;
import com.mes.cloud.exception.BaseException;
import com.mes.cloud.common.CommPager;
import com.mes.cloud.common.JsonResult;
import com.mes.cloud.constant.Constants;
import com.mes.cloud.constant.TreeConstants;
import com.mes.cloud.dao.BaseAreaDao;
import com.mes.cloud.dao.SysParamDao;
import com.mes.cloud.entity.BaseArea;
import com.mes.cloud.entity.SysAreaLog;
import com.mes.cloud.entity.SysParam;
import com.mes.cloud.entity.param.BaseAreaByIds;
import com.mes.cloud.entity.vo.BaseEmployeePositionVo;
import com.mes.cloud.entity.vo.area.BaseAreaDetailVo;
import com.mes.cloud.entity.vo.area.BaseAreaLevelVo;
import com.mes.cloud.enums.HttpStatusEnum;
import com.mes.cloud.util.DateUtil;
import com.mes.cloud.util.UserUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * 行政区划表
 *
 * @author Mr.zhang
 * @version 2019-07-29 18:14:59
 * @email 407892370@qq.com
 */
@Service
public class BaseAreaService {

    private BaseAreaDao baseAreaDao;
    private IPKeyGenerator iPKeyGenerator;
    private LogService logService;
    private SysCodeGeneratorService sysCodeGeneratorService;
    private SysParamDao sysParamDao;
    private SysPositionOrganizationAuthService sysPositionOrganizationAuthService;


    @Autowired
    public BaseAreaService(BaseAreaDao baseAreaDao,
                           IPKeyGenerator iPKeyGenerator,
                           LogService logService,
                           SysCodeGeneratorService sysCodeGeneratorService,
                           SysParamDao sysParamDao,
                           SysPositionOrganizationAuthService sysPositionOrganizationAuthService) {
        this.baseAreaDao = baseAreaDao;
        this.iPKeyGenerator = iPKeyGenerator;
        this.logService = logService;
        this.sysCodeGeneratorService = sysCodeGeneratorService;
        this.sysParamDao = sysParamDao;
        this.sysPositionOrganizationAuthService = sysPositionOrganizationAuthService;
    }

    /**
     * @description 根据父ID查询行政区划列表
     * @author dongyi
     * @date 2019-07-30 17:53
     **/
    public List<BaseAreaDto> selectAreaList(String parentId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("parentId", parentId);
        List<BaseArea> baseAreaList = baseAreaDao.list(paramMap);
        List<BaseAreaDto> baseAreaDtoList = new ArrayList<>();
        for (BaseArea baseArea : baseAreaList) {
            BaseAreaDto baseAreaDto = new BaseAreaDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            baseAreaDtoList.add(baseAreaDto);
        }
        return baseAreaDtoList;
    }

    /**
     * @description 新增行政区划
     * @author dongyi
     * @date 2019-08-01 09:15
     **/
    @Transactional(rollbackFor = Exception.class)
    public JsonResult insertSelective(BaseAreaRequest baseAreaRequest) {

        String parentId = baseAreaRequest.getParentId();
        JsonResult jsonResult = new JsonResult();
        BaseArea baseArea = new BaseArea();
        BeanUtils.copyProperties(baseAreaRequest, baseArea);
        baseArea.setId(iPKeyGenerator.getGenerateKey());
        baseArea.setUpdateDateStr(DateUtil.updateDateStr());
        baseArea.setCreateBy(UserUtil.getCreateByName());
        baseArea.setUpdateBy(UserUtil.getUpdateByName());
        baseArea.setCreateByNo(UserUtil.getCreateByNo());
        baseArea.setUpdateByNo(UserUtil.getUpdateByNo());

        //设置父亲组
        BaseArea baseAreaParent = baseAreaDao.selectByPrimaryKey(parentId);
        String parentGroup = "";
        // 如果上级是0，parentGroup=0
        if (TreeConstants.TOP_NODE_PARENTID_ZERO.equals(baseAreaRequest.getParentId())) {
            // 前面加逗号是为了like时索引生效
            parentGroup = "," + TreeConstants.TOP_NODE_PARENTID_ZERO;
        } else {
            parentGroup = baseAreaParent.getParentGroup() + "," + baseAreaParent.getId();
        }
        baseArea.setParentGroup(parentGroup);

        /*
         * 根据区划类别不同，区划编码也不同
         * 省：8位数字  城市：8位数字  区县：8数字
         * 乡镇：8数字   村/居委会: 12位数字
         */
        Long geneCode;
        String newCode;
        switch (baseArea.getType()) {
            case Constants.AREA_TYPE_COUNTRY:
                geneCode = Long.valueOf(sysCodeGeneratorService.getCode(Constants.CODE_GENERATOR_AREA));
                newCode = String.format("%08d", geneCode);
                baseArea.setCode(newCode);
                break;
            case Constants.AREA_TYPE_PROVINCE:
                geneCode = Long.valueOf(sysCodeGeneratorService.getCode(Constants.CODE_GENERATOR_AREA));
                newCode = String.format("%08d", geneCode);
                baseArea.setCode(newCode);
                break;
            case Constants.AREA_TYPE_CITY:
                geneCode = Long.valueOf(sysCodeGeneratorService.getCode(Constants.CODE_GENERATOR_AREA));
                newCode = String.format("%08d", geneCode);
                baseArea.setCode(newCode);
                break;
            case Constants.AREA_TYPE_DISTRICT:
                geneCode = Long.valueOf(sysCodeGeneratorService.getCode(Constants.CODE_GENERATOR_AREA));
                newCode = String.format("%08d", geneCode);
                baseArea.setCode(newCode);
                break;
            case Constants.AREA_TYPE_TOWN:
                geneCode = Long.valueOf(sysCodeGeneratorService.getCode(Constants.CODE_GENERATOR_AREA));
                newCode = String.format("%08d", geneCode);
                baseArea.setCode(newCode);
                break;
            case Constants.AREA_TYPE_VILLAGE:
                geneCode = Long.valueOf(sysCodeGeneratorService.getCode(Constants.CODE_GENERATOR_AREA));
                newCode = String.format("%012d", geneCode);
                baseArea.setCode(newCode);
                break;
        }
        // 设置父亲节点为非叶子节点
        if (baseAreaParent != null) {
            //设置父节点leafflag=0  不是叶子节点
            baseAreaParent.setLeafFlag(String.valueOf(Constants.NO));
            baseAreaParent.setUpdateDateStr(DateUtil.updateDateStr());
            baseAreaParent.setUpdateBy(UserUtil.getUpdateByName());
            baseAreaParent.setUpdateByNo(UserUtil.getUpdateByNo());
            baseAreaDao.updateByPrimaryKeySelective(baseAreaParent);
        }
        int count = baseAreaDao.insertSelective(baseArea);
        if (count > 0) {
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            // 插入操作日志
            this.insertLog(baseArea, Constants.ADD_AREA);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(), HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * @description 更新行政区划
     * @author dongyi
     * @date 2019-08-01 09:15
     **/
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateSelectiveById(BaseAreaRequest baseAreaRequest) {
        BaseArea baseArea = new BaseArea();
        BeanUtils.copyProperties(baseAreaRequest, baseArea);
        baseArea.setUpdateDateStr(DateUtil.updateDateStr());
        baseArea.setUpdateBy(UserUtil.getUpdateByName());
        baseArea.setUpdateByNo(UserUtil.getUpdateByNo());

        // 数据库中的旧数据
        BaseArea oldArea = baseAreaDao.selectByPrimaryKey(baseAreaRequest.getId());
        // 是否修改了父亲节点标识位
        boolean changeParentFlag = false;
        if (!StringUtils.isEmpty(oldArea.getParentId()) && !StringUtils.isEmpty(baseAreaRequest.getParentId()) && !baseAreaRequest.getParentId().equals(oldArea.getParentId())) {
            changeParentFlag = true;
            // 设置父亲组
            BaseArea baseAreaParent = baseAreaDao.selectByPrimaryKey(baseAreaRequest.getParentId());
            String parentGroup = "";
            // 如果上级是0，parentGroup=0
            if (TreeConstants.TOP_NODE_PARENTID_ZERO.equals(baseAreaRequest.getParentId())) {
                // 前面加逗号是为了like时索引生效
                parentGroup = "," + TreeConstants.TOP_NODE_PARENTID_ZERO;
            } else {
                parentGroup = baseAreaParent.getParentGroup() + "," + baseAreaParent.getId();
            }
            baseArea.setParentGroup(parentGroup);

            // 设置新父亲节点为非叶子节
            BaseArea baseAreaNewParent = baseAreaDao.selectByPrimaryKey(baseAreaRequest.getParentId());
            if (baseAreaNewParent != null) {
                //设置父节点leafflag=0  不是叶子节点
                baseAreaNewParent.setLeafFlag(String.valueOf(Constants.NO));
                baseAreaNewParent.setUpdateDateStr(DateUtil.updateDateStr());
                baseAreaNewParent.setUpdateBy(UserUtil.getUpdateByName());
                baseAreaNewParent.setUpdateByNo(UserUtil.getUpdateByNo());
                baseAreaDao.updateByPrimaryKeySelective(baseAreaNewParent);
            }
        }

        int count = baseAreaDao.updateByPrimaryKeySelective(baseArea);
        JsonResult jsonResult = new JsonResult();
        if (count > 0) {
            if (changeParentFlag) {
                // 判断旧的父亲节点是否有数据，如果没有数据的话，改为叶子节点
                BaseArea oldAreaParent = baseAreaDao.selectByPrimaryKey(oldArea.getParentId());
                if (oldAreaParent != null) {
                    BaseArea oldParentParam = new BaseArea();
                    oldParentParam.setParentId(oldAreaParent.getId());
                    oldParentParam.setEnableFlag(Constants.ENABLE_FLAG_YES);
                    oldParentParam.setDelFlag(Constants.DEL_FLAG_NO);
                    int oldParentCount = baseAreaDao.selectCount(oldParentParam);
                    if (oldParentCount <= 0) { // 如果没有儿子,该节点改为叶子节点
                        oldAreaParent.setLeafFlag(String.valueOf(Constants.YES));
                        oldAreaParent.setUpdateDateStr(DateUtil.updateDateStr());
                        oldAreaParent.setUpdateBy(UserUtil.getUpdateByName());
                        oldAreaParent.setUpdateByNo(UserUtil.getUpdateByNo());
                        baseAreaDao.updateByPrimaryKeySelective(oldAreaParent);
                    }
                }

                // 修改所有的儿子节点的parent_group
                BaseArea sonParam = new BaseArea();
                sonParam.setParentId(baseArea.getId());
                List<BaseArea> sonList = baseAreaDao.select(sonParam);
                if (!CollectionUtils.isEmpty(sonList)) {
                    recursionUpdateSubParentGroup(sonList);
                }
            }
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            // 插入操作日志
            this.insertLog(baseArea, Constants.UPDATE_AREA);
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(), HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * 递归更新子节点parent_group
     *
     * @param list
     */
    public void recursionUpdateSubParentGroup(List<BaseArea> list) {
        if (!CollectionUtils.isEmpty(list)) {
            for (BaseArea baseArea : list) {
                //获取父节点
                BaseArea parentAreaParam = new BaseArea();
                parentAreaParam.setId(baseArea.getParentId());
                BaseArea parentArea = baseAreaDao.selectByPrimaryKey(baseArea.getParentId());
                String parentGroup = "";
                if (parentArea != null) {
                    parentGroup = parentArea.getParentGroup() + "," + parentArea.getId();
                } else {
                    // 前面加逗号是为了like时索引生效
                    parentGroup = "," + TreeConstants.TOP_NODE_PARENTID_ZERO;
                }
                BaseArea updateArea = new BaseArea();
                updateArea.setId(baseArea.getId());
                updateArea.setParentGroup(parentGroup);
                updateArea.setUpdateDateStr(DateUtil.updateDateStr());
                updateArea.setUpdateBy(UserUtil.getUpdateByName());
                updateArea.setUpdateByNo(UserUtil.getUpdateByNo());
                baseAreaDao.updateByPrimaryKeySelective(updateArea);

                // 根据parentId找到所有的儿子节点
                BaseArea sonParam = new BaseArea();
                sonParam.setParentId(baseArea.getId());
                List<BaseArea> sonList = baseAreaDao.select(sonParam);
                if (!CollectionUtils.isEmpty(sonList)) {
                    // 递归更新
                    recursionUpdateSubParentGroup(sonList);
                }
            }
        }
    }

    /**
     * @description 启用禁用
     * @author dongyi
     * @date 2019-08-01 14:13
     **/
    @Transactional(rollbackFor = Exception.class)
    public JsonResult updateEnableFlag(String id, String enableFlag) {
        BaseArea baseArea = new BaseArea();
        baseArea.setId(id);
        baseArea.setEnableFlag(enableFlag);
        baseArea.setUpdateDateStr(DateUtil.updateDateStr());
        baseArea.setUpdateBy(UserUtil.getUpdateByName());
        baseArea.setUpdateByNo(UserUtil.getUpdateByNo());
        BaseArea oldBaseArea = baseAreaDao.selectByPrimaryKey(id);
        JsonResult jsonResult = new JsonResult();

        // 停用时，如果有儿子节点是可用状态，则不可停用
        if (Constants.ENABLE_FLAG_NO.equals(enableFlag)) {
            Map<String, Object> paramMap = new HashMap();
            paramMap.put("parentId", id);
            int sonCount = baseAreaDao.selectEnableCount(paramMap);
            if (sonCount > 0) {
                jsonResult.setMsg(HttpStatusEnum.AREA_CHILDREN_EXIST.getMessage());
                jsonResult.setCode(HttpStatusEnum.AREA_CHILDREN_EXIST.getCode());
                return jsonResult;
            }
        }
        int count = baseAreaDao.updateByPrimaryKeySelective(baseArea);
        if (count > 0) {
            // 停用时，如果父亲节点下无子节点，父节点改为叶子节点。启用时，父亲节点改为非叶子节点
            if (Constants.ENABLE_FLAG_NO.equals(enableFlag)) {
                // 停用时，如果父亲节点下无子节点，父节点改为叶子节点
                BaseArea baseAreaParent = baseAreaDao.selectByPrimaryKey(oldBaseArea.getParentId());
                if (baseAreaParent != null) {
                    BaseArea parentParam = new BaseArea();
                    parentParam.setParentId(baseAreaParent.getId());
                    parentParam.setEnableFlag(Constants.ENABLE_FLAG_YES);
                    parentParam.setDelFlag(Constants.DEL_FLAG_NO);
                    int parentCount = baseAreaDao.selectCount(parentParam);
                    if (parentCount <= 0) { // 如果没有儿子,该节点改为叶子节点
                        baseAreaParent.setLeafFlag(String.valueOf(Constants.YES));
                        baseAreaParent.setUpdateDateStr(DateUtil.updateDateStr());
                        baseAreaParent.setUpdateBy(UserUtil.getUpdateByName());
                        baseAreaParent.setUpdateByNo(UserUtil.getUpdateByNo());
                        baseAreaDao.updateByPrimaryKeySelective(baseAreaParent);
                    }
                }
            } else {
                // 设置新父亲节点为非叶子节
                BaseArea baseAreaParent = baseAreaDao.selectByPrimaryKey(oldBaseArea.getParentId());
                if (baseAreaParent != null) {
                    //设置父节点leafflag=0  不是叶子节点
                    baseAreaParent.setLeafFlag(String.valueOf(Constants.NO));
                    baseAreaParent.setUpdateDateStr(DateUtil.updateDateStr());
                    baseAreaParent.setUpdateBy(UserUtil.getUpdateByName());
                    baseAreaParent.setUpdateByNo(UserUtil.getUpdateByNo());
                    baseAreaDao.updateByPrimaryKeySelective(baseAreaParent);
                }
            }
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode());
            // 插入操作日志
            if (Constants.ENABLE_FLAG_NO == enableFlag) {
                this.insertLog(baseArea, Constants.DISABLE_AREA);
            } else {
                this.insertLog(baseArea, Constants.ENABLE_AREA);
            }
        } else {
            throw new BaseException(HttpStatusEnum.FAIL.getCode(), HttpStatusEnum.FAIL.getMessage());
        }
        return jsonResult;
    }

    /**
     * @description 根据编码或名称分页查询行政区划
     * @author dongyi
     * @date 2019-07-30 17:53
     **/
    public CommPager<BaseAreaDto> areaPageSearch(BaseAreaQueryPageRequest pageRequest) {
        Page<BaseAreaDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        //查询条件
        BaseArea selectParam = new BaseArea();
        BeanUtils.copyProperties(pageRequest, selectParam);
        Map<String, Object> paramMap = new HashMap<>();
        List<BaseArea> baseAreaList;
        // 判断parentId是否country，如果为country的话，取国家层面的数据
        paramMap.put("queryString", pageRequest.getQueryString());
        paramMap.put("parentId", pageRequest.getParentId());
        paramMap.put("enableFlag", pageRequest.getEnableFlag());
        baseAreaList = baseAreaDao.areaPageSearch(paramMap);
        List<BaseAreaDto> baseAreaDtoList = new ArrayList<>();
        for (BaseArea baseArea : baseAreaList) {
            BaseAreaDto baseAreaDto = new BaseAreaDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            baseAreaDtoList.add(baseAreaDto);
        }
        CommPager<BaseAreaDto> pageResult = new CommPager<>(page, baseAreaDtoList);
        return pageResult;
    }

    /**
     * @description 根据行政区划查找员工
     * @author dongyi
     * @date 2019-08-02 11:32
     **/
    public CommPager<BaseEmployeePositionDto> selectEmployeeListByArea(BaseAreaEmployeePageRequest pageRequest) {
        Page<BaseEmployeePositionDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());

        //String baseStation = baseAreaDao.selectAreaNameByAreaId(pageRequest.getAreaId());
        Map<String, Object> param = new HashMap<>();
        param.put("areaId", pageRequest.getAreaId());
        param.put("queryString", pageRequest.getQueryString());

        List<BaseEmployeePositionVo> employeeList = baseAreaDao.selectEmployeeListByArea(param);
        List<BaseEmployeePositionDto> areaEmployeeList = new ArrayList<>();
        for (BaseEmployeePositionVo employee : employeeList) {
            BaseEmployeePositionDto areaEmployeeDto = new BaseEmployeePositionDto();
            BeanUtils.copyProperties(employee, areaEmployeeDto);
            areaEmployeeList.add(areaEmployeeDto);
        }
        CommPager<BaseEmployeePositionDto> pageResult = new CommPager<>(page, areaEmployeeList);
        return pageResult;
    }

    /**
     * <功能详细描述>
     *
     * @param pageRequest
     * @return com.shinho.tntframe.core.common.model.JsonResult<com.shinho.tntframe.core.common.model.CommPager < com.shinho.crm.base.api.dto.response.BaseAreaDto>>
     * @author xy
     * @date 2019/8/3 10:35
     */
    public CommPager<BaseAreaDto> pageSysOrganizationArea(BaseOrganizationAreaPageRequest pageRequest) {
        Page<BaseAreaDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        Map<String, Object> param = new HashMap<>();
        param.put("organizationId", pageRequest.getOrganizationId());
        param.put("queryString", pageRequest.getQueryString());
        List<BaseArea> areaList = baseAreaDao.selectSysOrganizationArea(param);
        List<BaseAreaDto> areaEmployeeList = new ArrayList<>();
        for (BaseArea baseArea : areaList) {
            // 设置行政区划全名
            BaseArea bArea = baseAreaDao.selectByPrimaryKey(baseArea.getId());
            String areaFullName = baseAreaDao.getAreaFullName(bArea.getParentGroup() + "," + bArea.getId());
            baseArea.setName(areaFullName);
            BaseAreaDto baseAreaDto = new BaseAreaDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            areaEmployeeList.add(baseAreaDto);
        }
        CommPager<BaseAreaDto> pageResult = new CommPager<>(page, areaEmployeeList);
        return pageResult;
    }

    /**
     * @description 查询行政区划详情
     * @author dongyi
     * @date 2019-08-05 16:41
     **/
    public JsonResult<BaseAreaDto> selectAreaDetail(String areaId) {
        Map<String, Object> params = new HashMap<>();
        params.put("areaId", areaId);
        BaseAreaDetailVo areaDetail = baseAreaDao.selectAreaDetail(params);
        JsonResult<BaseAreaDto> jsonResult = new JsonResult();
        if (areaDetail != null) {
            BaseAreaDto baseAreaDto = new BaseAreaDto();
            // 去除最前面的0（全部）
            String parentGroup = areaDetail.getParentGroup().replaceFirst("0,", "");
            areaDetail.setParentGroup(parentGroup);
            BeanUtils.copyProperties(areaDetail, baseAreaDto);
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaDto);
        } else {
            jsonResult.setMsg(HttpStatusEnum.RECORD_NOT_EXIST.getMessage()).setCode(HttpStatusEnum.RECORD_NOT_EXIST.getCode());
        }
        return jsonResult;
    }

    /**
     * @description 添加操作日志
     * @author dongyi
     * @date 2019-08-07 13:36
     **/
    private int insertLog(BaseArea baseArea, String logMessage) {
        SysAreaLog sysAreaLog = new SysAreaLog();
        sysAreaLog.setAreaId(baseArea.getId());
        sysAreaLog.setMenuCode(Constants.AREA_MENU_CODE);
        sysAreaLog.setLog(logMessage);
        sysAreaLog.setId(iPKeyGenerator.getGenerateKey());
        sysAreaLog.setUpdateDateStr(DateUtil.updateDateStr());
        sysAreaLog.setCreateBy(UserUtil.getCreateByName());
        sysAreaLog.setUpdateBy(UserUtil.getUpdateByName());
        sysAreaLog.setCreateByNo(UserUtil.getCreateByNo());
        sysAreaLog.setUpdateByNo(UserUtil.getUpdateByNo());
        return logService.insertAreaLog(sysAreaLog);
    }

    /**
     * @description 根据层级查询行政区划列表
     * @author dongyi
     * @date 2019-08-08 16:00
     **/
    public JsonResult<List<BaseAreaLevelDto>> levelList(Integer level) {
        JsonResult<List<BaseAreaLevelDto>> jsonResult = new JsonResult();
        // 判断level是否合规
        if (level == null || (level != 1 && level != 2 && level != 3 && level != 4 && level != 5)) {
            jsonResult.setMsg(HttpStatusEnum.BAD_REQUEST.getMessage()).setCode(HttpStatusEnum.BAD_REQUEST.getCode());
            return jsonResult;
        }
        List<BaseAreaLevelVo> baseAreaList = baseAreaDao.listLevel(level);
        List<BaseAreaLevelDto> baseAreaLevelList = new ArrayList<>();
        for (BaseAreaLevelVo baseArea : baseAreaList) {
            BaseAreaLevelDto baseAreaDto = new BaseAreaLevelDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            baseAreaLevelList.add(baseAreaDto);
        }
        return jsonResult.setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaLevelList);
    }

    /**
     * <组织查询行政区划>
     *
     * @param organizationId
     * @return JsonResult<List < BaseAreaDto>>
     * @author xy
     * @date 2019/8/30 11:53
     */
    public JsonResult<List<BaseAreaLevelDto>> areaListByOrganizationId(String organizationId) {
        JsonResult<List<BaseAreaLevelDto>> jsonResult = new JsonResult();
        //查询有效区域数据
        List<BaseAreaLevelVo> baseAreaList = baseAreaDao.listLevel(Constants.AREA_TYPE_DISTRICT);
        List<BaseAreaLevelDto> baseAreaDtoList = new ArrayList<>();
        for (BaseAreaLevelVo baseArea : baseAreaList) {
            BaseAreaLevelDto baseAreaDto = new BaseAreaLevelDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            baseAreaDtoList.add(baseAreaDto);
        }
        //查询组织关联的区域数据 只查询区域禁用状态的数据
        List<BaseAreaLevelVo> orgAreaList = baseAreaDao.areaListByOrganizationId(organizationId);
        List<BaseAreaLevelDto> orgAreaDtoList = new ArrayList<>();
        for (BaseAreaLevelVo baseArea : orgAreaList) {
            BaseAreaLevelDto baseAreaDto = new BaseAreaLevelDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            orgAreaDtoList.add(baseAreaDto);
        }
        List<BaseAreaLevelDto> listAll = new ArrayList<>();
        listAll.addAll(baseAreaDtoList);
        listAll.addAll(orgAreaDtoList);
        return jsonResult.setCode(HttpStatusEnum.OK.getCode()).setData(listAll);
    }

    public JsonResult<List<BaseAreaDto>> excludeQueryAreaList(BaseAreaListRequest request) {
        JsonResult<List<BaseAreaDto>> jsonResult = new JsonResult<>();

        List<BaseArea> baseAreaList = baseAreaDao.excludeQueryAreaList(request);
        List<BaseAreaDto> baseAreaDtoList = new ArrayList<>();
        for (BaseArea baseArea : baseAreaList) {
            BaseAreaDto baseAreaDto = new BaseAreaDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            baseAreaDtoList.add(baseAreaDto);
        }
        return jsonResult.setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaDtoList);

    }

    /**
     * @description 根据员工查询授权组织的所有行政区划，
     * 并且取出对应的上级，保持树的结构
     * @author dongyi
     * @date 2019-11-05 11:37
     **/
    public JsonResult<List<BaseAreaByEmployeeDto>> areaListByEmployee() {
        List<BaseAreaByEmployeeDto> baseAreaDtoList = new ArrayList<>();
        JsonResult<List<BaseAreaByEmployeeDto>> jsonResult = new JsonResult<>();
        // 1、查看当前登录人的授权组织是否在配置的组织中，如果在，就查询全国的数据
        if (allAreaFlag()) {
            Map paramMap = new HashMap();
            paramMap.put("parentId", "CN");
            List<BaseArea> baseAreaList = baseAreaDao.list(paramMap);
            // 把中国的数据加进去
            BaseArea baseParam = new BaseArea();
            baseParam.setId("CN");
            BaseArea cnArea = baseAreaDao.selectOne(baseParam);
            baseAreaList.add(cnArea);
            for (BaseArea baseArea : baseAreaList) {
                BaseAreaByEmployeeDto baseAreaDto = new BaseAreaByEmployeeDto();
                BeanUtils.copyProperties(baseArea, baseAreaDto);
                baseAreaDtoList.add(baseAreaDto);
            }
            return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaDtoList);
        }

        // 2、正常的查询逻辑
        String employeeId = UserUtil.getEmployeeId();
        // 获取行政区划的id以及parent_group
        List<BaseArea> baseAreaList = baseAreaDao.getAreaByEmployee(employeeId);
        Set<String> areaIdSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(baseAreaList)) {
            // 将行政区划的id和父id都存入set中，去重。
            for (BaseArea area : baseAreaList) {
                areaIdSet.add(area.getId());
                List<String> groupList = Arrays.asList(StringUtils.split(area.getParentGroup(), ","));
                for (String parentId : groupList) {
                    areaIdSet.add(parentId);
                }
            }
            List<String> ids = new ArrayList<>(areaIdSet);
            BaseAreaByIds baseAreaByIds = new BaseAreaByIds();
            baseAreaByIds.setIds(ids);

            // 根据多个ID查询行政区划
            List<BaseArea> areaList = baseAreaDao.listByIds(baseAreaByIds);
            for (BaseArea baseArea : areaList) {
                BaseAreaByEmployeeDto baseAreaDto = new BaseAreaByEmployeeDto();
                BeanUtils.copyProperties(baseArea, baseAreaDto);
                // 如果二次查询出来的行政区划，在组织-行政区划关联中不存在，就标记为补充
                baseAreaDto.setSupplementFlag(Constants.YES);
                for (int i = 0; i < baseAreaList.size(); i++) {
                    if (baseArea.getId().equals(baseAreaList.get(i).getId())) {
                        baseAreaDto.setSupplementFlag(Constants.NO);
                    }
                }
                baseAreaDtoList.add(baseAreaDto);
            }
            return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaDtoList);
        }
        return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaDtoList);
    }


    /**
     * @description 查询当前员工数据权限下的行政区划的所有下级，只到组织关联的行政区划表的级别，即区县级别
     * @author dongyi
     * @date 2019-11-09 09:31
     **/
    public JsonResult<List<BaseAreaDto>> getSonAreaByEmployee(String areaId) {
        JsonResult jsonResult = new JsonResult<>();
        String employeeId = UserUtil.getEmployeeId();
        // 查询当前员工数据权限下的行政区划的所有下级
        List<BaseArea> baseAreaList = baseAreaDao.getSonAreaByEmployee(employeeId, areaId);
        List<BaseAreaDto> baseAreaDtoList = new ArrayList<>();
        for (BaseArea baseArea : baseAreaList) {
            BaseAreaDto baseAreaDto = new BaseAreaDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            baseAreaDtoList.add(baseAreaDto);
        }
        return jsonResult.setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaDtoList);
    }

    /**
     * @description 查询当前员工数据权限下的行政区划的所有下级, 到最后一级，即村级别
     * @author dongyi
     * @date 2019-07-30 17:53
     **/
    public JsonResult<CommPager<BaseAreaAllSonDto>> getAllSonAreaByEmployee(BaseAreaQueryPageRequest pageRequest) {
        List<BaseAreaAllSonDto> baseAreaDtoList = new ArrayList<>();
        //查询条件
        String employeeId = UserUtil.getEmployeeId();
        String queryString = pageRequest.getQueryString();
        String parentId = pageRequest.getParentId();
        // 1、查看当前登录人的授权组织是否在配置的组织中，如果在，就查询全国的数据
        if (allAreaFlag()) {
            BaseAreaByIds baseAreaByIds = new BaseAreaByIds();
            baseAreaByIds.setRegexpString("^0,CN");
            baseAreaByIds.setQueryString(queryString);
            baseAreaByIds.setParentId(parentId);

            // 查询当前员工数据权限下的行政区划的所有下级,这里组织-行政区划关联表中的级别，即区县级别
            Page<BaseAreaAllSonDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
            List<BaseArea> lastBaseAreaList = baseAreaDao.getAllSonAreaSpecial(baseAreaByIds);
            for (BaseArea baseArea : lastBaseAreaList) {
                BaseAreaAllSonDto baseAreaDto = new BaseAreaAllSonDto();
                BeanUtils.copyProperties(baseArea, baseAreaDto);
                baseAreaDtoList.add(baseAreaDto);
            }
            CommPager<BaseAreaAllSonDto> pageResult = new CommPager<>(page, baseAreaDtoList);
            JsonResult<CommPager<BaseAreaAllSonDto>> jsonResult = new JsonResult<>();
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
            return jsonResult;
        }


        // 2、正常查询的逻辑
        // 查询当前员工数据权限下的行政区划的所有下级,这里组织-行政区划关联表中的级别，即区县级别
        List<BaseArea> baseAreaList = baseAreaDao.getSonAreaByEmployee(employeeId, "");
        if (!CollectionUtils.isEmpty(baseAreaList)) {
            // 定义两个set，一个存放包含自己的parent_group，将上述list中所有的parent_group+id拼接后，并且想上取最大级别的，其他
            // 下级的删除。如有两个值，（中国，山东，烟台）和（中国，山东），只保留（中国，山东）
            List<String> parentGroupList = new ArrayList<>();
            List<String> selfList = new ArrayList<>();
            for (BaseArea baseArea : baseAreaList) {
                parentGroupList.add(baseArea.getParentGroup() + ',' + baseArea.getId());
            }
            // 遍历parentGroupList，如果存在当前parent_group的上级，将该parent_group存放在移除列表中
            List<String> removeParentGroupList = new ArrayList<>();
            for (String allParentGroup : parentGroupList) {
                for (String bigParentGroup : parentGroupList) {
                    if (allParentGroup.contains(bigParentGroup) && !allParentGroup.equals(bigParentGroup)) {
                        removeParentGroupList.add(allParentGroup);
                        break;
                    }
                }
            }

            // 移除不需要的parent_group
            parentGroupList.removeAll(removeParentGroupList);
            // 将最后一级存放到self数组中，这些要和base_area表中的id匹配
            StringBuffer regexpStrBuffer = new StringBuffer();
            for (String self : parentGroupList) {
                // 拼接查询的正则表达式
                regexpStrBuffer.append("^" + self + "|");
                selfList.add(self.substring(self.lastIndexOf(",") + 1));
            }
            String regexpStr = regexpStrBuffer.toString();
            if (!StringUtils.isEmpty(regexpStr)) {
                regexpStr = regexpStr.substring(0, regexpStr.lastIndexOf("|"));
            }

            BaseAreaByIds baseAreaByIds = new BaseAreaByIds();
            baseAreaByIds.setIds(selfList);
            baseAreaByIds.setRegexpString(regexpStr);
            baseAreaByIds.setQueryString(queryString);
            baseAreaByIds.setParentId(parentId);
            // 查询当前员工数据权限下的行政区划的所有下级,这里组织-行政区划关联表中的级别，即村级别
            Page<BaseAreaAllSonDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
            List<BaseArea> lastBaseAreaList = baseAreaDao.getAllSonAreaByEmployee(baseAreaByIds);

            for (BaseArea baseArea : lastBaseAreaList) {
                BaseAreaAllSonDto baseAreaDto = new BaseAreaAllSonDto();
                BeanUtils.copyProperties(baseArea, baseAreaDto);
                baseAreaDtoList.add(baseAreaDto);
            }
            CommPager<BaseAreaAllSonDto> pageResult = new CommPager<>(page, baseAreaDtoList);
            JsonResult<CommPager<BaseAreaAllSonDto>> jsonResult = new JsonResult<>();
            jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
            return jsonResult;
        }
        Page<BaseAreaAllSonDto> page = PageHelper.startPage(pageRequest.getCurrentPage(), pageRequest.getPageSize());
        CommPager<BaseAreaAllSonDto> pageResult = new CommPager<>(page, baseAreaDtoList);
        JsonResult<CommPager<BaseAreaAllSonDto>> jsonResult = new JsonResult<>();
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(pageResult);
        return jsonResult;
    }

    /**
     * 描述 当前员工， 授权组织下的所有行政区划
     *
     * @param
     * @return com.shinho.tntframe.core.common.model.JsonResult<java.util.List   <   com.shinho.crm.base.api.dto.response.area.BaseAreaDto>>
     * @author 郑样平
     * @date 2019/11/8 11:34
     */
    public JsonResult<List<BaseAreaDto>> areaEmployeeList() {
        JsonResult jsonResult = new JsonResult<>();
        String employeeId = UserUtil.getEmployeeId();
        // 获取行政区划的id以及parent_group
        List<BaseArea> baseAreaList = baseAreaDao.getAreaByEmployee(employeeId);
        List<BaseAreaDto> baseAreaDtoList = new ArrayList<>();
        for (BaseArea baseArea : baseAreaList) {
            BaseAreaDto baseAreaDto = new BaseAreaDto();
            BeanUtils.copyProperties(baseArea, baseAreaDto);
            baseAreaDtoList.add(baseAreaDto);
        }
        return jsonResult.setCode(HttpStatusEnum.OK.getCode()).setData(baseAreaDtoList);
    }

    /**
     * @description 判断当前登录人是否是查询全国行政区划的权限
     * @author dongyi
     * @date 2019-11-12 08:54
     **/
    private boolean allAreaFlag() {
        // 查看当前登录人的授权组织是否在配置的组织中，如果在，就查询全国的数据
        // 参数列表中，可以查询全国区划的组织ID
        SysParam selectParam = new SysParam();
        selectParam.setCode(Constants.ALL_AREA_ORG);
        SysParam sysParam = sysParamDao.selectOne(selectParam);
        String orgs = sysParam.getValue();
        if (StringUtils.isEmpty(orgs)) {
            return false;
        }

        JsonResult<List<String>> orgResult = sysPositionOrganizationAuthService.getOrganizationIdList();
        if (orgResult != null && !CollectionUtils.isEmpty(orgResult.getData())) {
            List<String> orgList = orgResult.getData();
            for (String org : orgList) {
                // 如果包含控制全国的组织，用全国范围内查询，然后返回给前端
                if (orgs.contains(org)) {
                    return true;
                }
            }
        }
        return false;
    }

    public JsonResult<List<BaseAreaDto>> findListBySynchro(List<String> areaNames) {
        JsonResult jsonResult = new JsonResult<>();
        List<BaseArea> baseAreas = baseAreaDao.findListBySynchro(areaNames);
        List<BaseAreaDto> dtoList = new ArrayList<>();
        for (BaseArea baseArea : baseAreas) {
            BaseAreaDto dto = new BaseAreaDto();
            BeanUtils.copyProperties(baseArea,dto);
            dtoList.add(dto);
        }
        jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(dtoList);
        return jsonResult;
    }

        public JsonResult<String> allAreaFlag1() {
        JsonResult jsonResult = new JsonResult();
        String str ="";
        // 查看当前登录人的授权组织是否在配置的组织中，如果在，就查询全国的数据
        // 参数列表中，可以查询全国区划的组织ID
        SysParam selectParam = new SysParam();
        selectParam.setCode(Constants.ALL_AREA_ORG);
        SysParam sysParam = sysParamDao.selectOne(selectParam);
        String orgs = sysParam.getValue();
        if (StringUtils.isEmpty(orgs)) {
            str=Constants.ENABLE_FLAG_NO;
          return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(str);
        }

        JsonResult<List<String>> orgResult = sysPositionOrganizationAuthService.getOrganizationIdList();
        if (orgResult != null && !CollectionUtils.isEmpty(orgResult.getData())) {
            List<String> orgList = orgResult.getData();
            for (String org : orgList) {
                // 如果包含控制全国的组织，用全国范围内查询，然后返回给前端
                if (orgs.contains(org)) {
                    str=Constants.ENABLE_FLAG_YES;
                    return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(str);
                }
            }
        }
        return jsonResult.setMsg(HttpStatusEnum.OK.getMessage()).setCode(HttpStatusEnum.OK.getCode()).setData(str);
    }

}
